<?php  
class ControllerProduct extends Controller {
	function index() { 
		$cart     =& $this->locator->get('cart');
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$image    =& $this->locator->get('image');
		$module   =& $this->locator->get('module');
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$shipping =& $this->locator->get('shipping');
		$tax      =& $this->locator->get('tax');
		$template =& $this->locator->get('template');
		$url      =& $this->locator->get('url');
    	
    	if ($request->isPost() && $request->has('product_id', 'post')) {
      		$cart->add($request->gethtml('product_id', 'post'), ($request->gethtml('quantity', 'post') > 0) ? $request->gethtml('quantity', 'post') : 1, $request->gethtml('option', 'post'));
 
      		$response->redirect($url->href('cart'));
    	}

    	$language->load('controller/product.php');
		
		$view = $this->locator->create('template');

		$view->set('tpl', $template);
		
		$product_info = $database->getRow("select * from product p left join product_description pd on (p.product_id = pd.product_id) left join image i on (p.image_id = i.image_id) where p.product_id = '" . (int)$request->gethtml('product_id') . "' and pd.language_id = '" . (int)$language->getId() . "' and p.date_available < now() and p.status = '1'");
    	
		if ($product_info) {
      		$database->query("update product set viewed = viewed + 1 where product_id = '" . (int)$request->gethtml('product_id') . "'");

      		$breadcrumb = array();

      		$breadcrumb[] = array(
        		'href'      => $url->href('home'),
        		'text'      => $language->get('text_home'),
        		'separator' => FALSE
      		);

      		if ($request->gethtml('path')) {
        		foreach (explode('_', $request->gethtml('path')) as $category_id) {
          			$category_info = $database->getRow("select cd.name, c.path from category c left join category_description cd on c.category_id = cd.category_id where c.category_id = '" . (int)$category_id . "' and cd.language_id = '" . (int)$language->getId() . "'");

          			$breadcrumb[] = array(
						'href'      => $url->href('category', FALSE, array('path' => $category_info['path'])),
            			'text'      => $category_info['name'],
            			'separator' => $language->get('text_separator')
          			);
        		}
      		}

      		$query = array(
        		'path'       => $request->gethtml('path'),
        		'product_id' => $request->gethtml('product_id')
      		);

      		$breadcrumb[] = array(
        		'href'      => $url->href('product', FALSE, $query),
        		'text'      => $product_info['name'],
        		'separator' => $language->get('text_separator')
      		);

	  		$template->set('title', $product_info['name']);
	  		      		
      		$view->set('heading_title', $product_info['name']);

      		$view->set('text_enlarge', $language->get('text_enlarge'));
      		$view->set('text_images', $language->get('text_images'));
      		$view->set('text_options', $language->get('text_options'));
            $view->set('text_min_qty', $language->get('text_min_qty'));
            $view->set('text_add_to_cart', $language->get('text_add_to_cart'));
			$view->set('text_model', $language->get('text_model'));
			$view->set('text_weight', $language->get('text_weight'));
			$view->set('text_stock', $language->get('text_stock'));
			$view->set('text_manufacturer', $language->get('text_manufacturer'));
            $view->set('text_qty_discount', $language->get('text_qty_discount'));
            $view->set('text_qty', $language->get('text_qty'));
            $view->set('text_rate', $language->get('text_rate'));
            $view->set('text_disc', $language->get('text_disc'));
            $view->set('text_plus', $language->get('text_plus'));
            $view->set('text_related', $language->get('text_related'));
            
      		$view->set('button_reviews', $language->get('button_reviews'));
      		$view->set('button_add_to_cart', $language->get('button_add_to_cart'));

      		$view->set('breadcrumbs', $breadcrumb);

      		$query = array(
        		'path'       => $request->gethtml('path'),
        		'product_id' => $request->gethtml('product_id')
      		);

     		$view->set('action', $url->href('product', FALSE, $query));

      		$view->set('popup', $image->href($product_info['filename']));
      
	  		$view->set('thumb', $image->resize($product_info['filename'], $config->get('config_image_width_product'), $config->get('config_image_height_product')));

	  		$product_special = $database->getRow("SELECT * FROM product_special WHERE product_id = '" . (int)$product_info['product_id'] . "' AND date_start <= NOW() AND date_end > NOW() and status = '1'");
								
			if ($product_special && $product_special['prefix']) {
				$price = $product_info['price'];
				if ($product_special['prefix'] == '%') {
					$price -= $price * ($product_special['discount']/100);
				} elseif ($product_special['prefix'] == '-') {
					$price -= $product_special['discount'];
				} else {
					$price = $product_special['discount'];
				}
      			$view->set('price_old', $currency->format($tax->calculate($product_info['price'], $product_info['tax_class_id'], $config->get('config_tax'))));
      			$view->set('price', $currency->format($tax->calculate($price, $product_info['tax_class_id'], $config->get('config_tax'))));
			} else {
      			$view->set('price_old', FALSE);
      			$view->set('price', $currency->format($tax->calculate($product_info['price'], $product_info['tax_class_id'], $config->get('config_tax'))));
			}
            
            $view->set('min_qty', isset($product_info['min_qty'])?$product_info['min_qty']:'');
            
      		$view->set('description', $product_info['description']);
      		
      		$view->set('model', $product_info['model']);
      		
      		$view->set('stock', $product_info['quantity']);
      		
      		$view->set('weight', $product_info['weight']);

      		$view->set('product_id', $request->gethtml('product_id'));

      		$view->set('review', $url->href('review', FALSE, array('product_id' => $request->gethtml('product_id'))));
			
			// Meta Info
      		$product_meta = $database->getRow("select * from product_meta where product_id = '" . (int)$request->gethtml('product_id') . "' and language_id = '" . (int)$language->getId() . "'");
      		      	
      		$template->set('meta_keys', $product_meta['keywords']);
      		
      		$template->set('meta_description', $product_meta['description']);
      		
      		// Review Info
      		$product_review = $database->getRow("select AVG(rating) as rating from review where product_id = '" . (int)$request->gethtml('product_id') . "' and status = '1'");
      		$view->set('rating', ceil($product_review['rating']));
      		$view->set('text_rating', $language->get('text_rating'));
  			$view->set('text_rating_stars', $language->get('text_rating_stars', ceil($product_review['rating'])));
      		
      		// Qty Discounts
      		$product_discounts = array();

      		$results = $database->getRows("select * from product_discount where product_id = '" . (int)$request->gethtml('product_id') . "' order by quantity asc");
			
			foreach($results as $result){
				$product_discounts[] = array(
					'quantity' => $result['quantity'],
					'rate' => $currency->format($tax->calculate(($product_info['price'] - $result['discount']), $product_info['tax_class_id'], $config->get('config_tax'))),
					'disc' => $currency->format($tax->calculate($result['discount'], $product_info['tax_class_id'], $config->get('config_tax')))
				);
			}
				
			$view->set('product_discounts', $product_discounts);
      		
      		      		
      		// Options
      		$options = array();

      		$results = $database->getRows("select * from product_to_option where product_id = '" . (int)$request->gethtml('product_id') . "' order by sort_order");

      		foreach ($results as $result) {
        		$options[$result['option_id']][] = array(
          			'product_to_option_id' => $result['product_to_option_id'],
          			'option_value_id'      => $result['option_value_id'],
          			'price'                => $result['price'],
          			'prefix'               => $result['prefix']
        		);
      		}

      		$option_data = array();

      		foreach ($options as $key => $values) {
        		$option_value_data = array();

        		foreach ($values as $value) {
          			$option_value_info = $database->getRow("select * from option_value where option_value_id = '" . (int)$value['option_value_id'] . "' and option_id = '" . (int)$key . "' and language_id = '" . (int)$language->getId() . "'");

          			$option_value_data[] = array(
            			'product_to_option_id' => $value['product_to_option_id'],
            			'option_value_id'      => $value['option_value_id'],
            			'name'                 => $option_value_info['name'],
            			'price'                => (($value['price'] != '0.00') ? $currency->format($tax->calculate($value['price'], $product_info['tax_class_id'], $config->get('config_tax'))) : null),
            			'prefix'               => $value['prefix']
          			);
        		}

        		$option = $database->getRow("select * from `option` where option_id = '" . (int)$key . "' and language_id = '" . (int)$language->getId() . "'");

        		$option_data[] = array(
          			'option_id' => $key,
          			'name'      => $option['name'],
          			'value'     => $option_value_data
        		);
      		}

      		$view->set('options', $option_data);

      		
      		// Extra Images
      		$image_data = array();

      		$results = $database->getRows("select i.image_id, i.filename, id.title from image i left join image_description id on (i.image_id = id.image_id) left join product_to_image p2i on (i.image_id = p2i.image_id) where p2i.product_id = '" . (int)$request->gethtml('product_id') . "' and id.language_id = '" . (int)$language->getId() . "'");

      		foreach ($results as $result) {
        		$image_data[] = array(
          			'title' => $result['title'],
          			'popup' => $image->href($result['filename']),
          			'thumb' => $image->resize($result['filename'], $config->get('config_image_width_images'), $config->get('config_image_height_images')),
        		);
      		}

      		$view->set('images', $image_data);
      		
      		
      		// Related Products
      		$related_data = array();

      		$results = $database->getRows("select p.product_id, i.filename, pd.name from product_related pr left join product p on (pr.related_id = p.product_id) left join product_description pd on (pr.related_id = pd.product_id) left join image i on (p.image_id = i.image_id) where pr.product_id = '" . (int)$request->gethtml('product_id') . "' and pd.language_id = '" . (int)$language->getId() . "'");

      		foreach ($results as $result) {
        		
        		$related_data[] = array(
          			'title' => $result['name'],
          			'href'  => $url->href('product', FALSE, array('product_id' => $result['product_id'])),
          			'thumb' => $image->resize($result['filename'], $config->get('config_image_width'), $config->get('config_image_height')),
        		);
      		}
      		
       		$view->set('related', $related_data);
      		
      		$view->set('disable_reviews', $config->get('config_disable_reviews'));
	  
	  		$template->set($module->fetch());
	  	  
	  		$template->set('content', $view->fetch('content/product.tpl'));
	  
	  		$response->set($template->fetch('layout.tpl'));
    	} else {
      		$template->set('title', $language->get('text_error'));

      		$view->set('heading_title', $language->get('text_error'));

      		$view->set('text_error', $language->get('text_error'));

      		$view->set('button_continue', $language->get('button_continue'));

      		$view->set('continue', $url->href('home'));
      
	  		$template->set($module->fetch());
	  	  
	  		$template->set('content', $view->fetch('content/error.tpl'));
	  
	  		$response->set($template->fetch('layout.tpl'));	
    	}
  	}
}
?>
